package isquirrel.servlets;

import java.io.IOException;

import javax.servlet.ServletException;

import org.json.JSONException;
import org.json.JSONObject;

import isquirrel.Logger;
import isquirrel.UserManager;
import isquirrel.beans.User;
import isquirrel.servlets.handler.HttpDBServlet;
import isquirrel.util.HibernateUtil;

/**
 * Servlet implementation class AddFriend
 */
public class AddFriend extends HttpDBServlet {
	private static final long serialVersionUID = 1L;

    /**
     * Default constructor. 
     */
    public AddFriend() {
    }

	@Override
	protected void handleGet() throws ServletException, IOException,
			JSONException {
		
	}

	@Override
	protected void handlePost() throws ServletException, IOException,
			JSONException {
		
		String friend_id = request.getParameter("friend_id");
		User user = getLoggedInUser();
		User new_friend = UserManager.getUser(Long.parseLong(friend_id));
		//check if the friend we're about to remove from this user is actually their friend
		JSONObject jsonResponse = new JSONObject();
		if (!user.getFriends().contains(new_friend)) {
			user.addFriend(new_friend);
			jsonResponse.put("error", "0");
		} else {
			jsonResponse.put("error", "1");
		}
		
		jsonResponse.put("friend_id", friend_id);
		HibernateUtil.getSession().saveOrUpdate(user);
		Logger.log(user, "added friend");
		writeAjaxResponse(jsonResponse);
		
	}

}
